﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace yaTDL.Core.MVVM
{

    //found here: http://elegantcode.com/2009/05/14/write-a-sortable-observablecollection-for-wpf/ Thanks!
    public class SortableObservableCollection<T> : ObservableCollection<T>
    {
        [DebuggerStepThrough()]
        public SortableObservableCollection()
            : base()
        {
        }

        [DebuggerStepThrough()]
        public SortableObservableCollection(List<T> list)
            : base(list)
        {
        }

        [DebuggerStepThrough()]
        public SortableObservableCollection(IEnumerable<T> collection)
            : base(collection)
        {
        }

        public void Sort<TKey>(Func<T, TKey> keySelector, System.ComponentModel.ListSortDirection direction)
        {
            switch (direction)
            {
                case System.ComponentModel.ListSortDirection.Ascending:
                    {
                        ApplySort(Items.OrderBy(keySelector));
                        break;
                    }
                case System.ComponentModel.ListSortDirection.Descending:
                    {
                        ApplySort(Items.OrderByDescending(keySelector));
                        break;
                    }
            }
        }

        public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
        {
            ApplySort(Items.OrderBy(keySelector, comparer));
        }

        private void ApplySort(IEnumerable<T> sortedItems)
        {
            try
            {
                var sortedItemsList = sortedItems.ToList();

                foreach (var item in sortedItemsList)
                {
                    Move(IndexOf(item), sortedItemsList.IndexOf(item));
                }
            }
            catch (Exception)
            {                             
            }

        }
    }
}
